from re import M


class Solution:
    def spiralOrder(self, matrix):
        m = len(matrix)
        n = len(matrix[0])

        if m == 1: 
            return matrix[0]
        
        if n == 1:
            return [matrix[i][0] for i in range(m)]
        
        ans = []

        count = m*n

        def helper(r1, r2, c1, c2):
            nonlocal count
            # 第一行
            j = c1
            while count > 0 and j <= c2:
                ele = matrix[r1][j]
                ans.append(ele)
                count -= 1
                j += 1
            
            # 最右列
            i = r1 + 1
            while count > 0 and i <= r2:
                ele = matrix[i][c2]
                ans.append(ele)
                count -= 1
                i += 1
            
            # 最底行
            j = c2 - 1
            while count > 0 and j >= c1:
                ele = matrix[r2][j]
                ans.append(ele)
                count -= 1
                j -= 1
            
            i = r2 - 1
            while count > 0 and i >= r1 + 1:
                ele = matrix[i][c1]
                ans.append(ele)
                count -= 1
                i -= 1
        
        r1, r2 = 0, m - 1
        c1, c2 = 0 , n - 1
        while count > 0:
            helper(r1, r2, c1, c2)
            r1 += 1
            r2 -= 1
            c1 += 1
            c2 -= 1
        
        return ans
               
if __name__ == '__main__':
    s = Solution()
    matrix = [[3],[2]]
    s.spiralOrder(matrix=matrix)